package handler

import (
	"2301a/yuekao/api/request"
	"2301a/yuekao/internal/dao"
	"2301a/yuekao/internal/model"
	"github.com/gin-gonic/gin"
	"net/http"
)

func AddOrder(c *gin.Context) {
	var req request.AddOrderReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var user model.User
	dao.GetOneById(c.GetUint("userId"), &user)
	if user.Id != 1 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "该权限不足",
			"data":    nil,
		})
		return
	}
	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "房源不存在",
			"data":    nil,
		})
		return
	}
	order := model.Order{
		UserId:     c.GetUint("userId"),
		HouseId:    req.HouseId,
		Price:      house.Price,
		PictureUrl: house.PictureUrl,
	}
	dao.Create(&order)
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "购房订单成功",
		"data":    order,
	})

}

func VoucherOrder(c *gin.Context) {
	var req request.VoucherOrderReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var house model.House
	dao.GetOneById(req.HouseId, &house)
	if house.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "房源不存在",
			"data":    nil,
		})
		return
	}

	dao.Update(&model.Order{HouseId: req.HouseId, PictureUrl: req.PictureUrl, Status: 2})
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "首付款凭证成功",
		"data":    true,
	})
}

func DetailsOrder(c *gin.Context) {
	var req request.DetailsOrderReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var order model.Order
	dao.GetOneById(req.Id, &order)
	if order.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "订单不存在",
			"data":    nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "查看订单成功",
		"data":    order,
	})
}

func UpdateOrder(c *gin.Context) {
	var req request.UpdateOrderReq

	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "参数信息错误",
			"data":    err.Error(),
		})
		return
	}
	var order model.Order
	dao.GetOneById(req.Id, &order)
	if order.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code":    100000,
			"message": "订单不存在",
			"data":    nil,
		})
		return
	}
	dao.Update(&model.Order{Id: req.Id, Status: req.Status})
	c.JSON(http.StatusOK, gin.H{
		"code":    http.StatusOK,
		"message": "更新订单成功",
		"data":    true,
	})
}
